﻿using UnityEngine;
using System.Collections;

public class Shoot : MonoBehaviour {
    public int damagePerShot = 20;
    public float range = 100f;
    public float shootRate = 5;
    private float shootTimer = 0f;
    private ParticleSystem ps;
    private LineRenderer line;

    void Awake()
    {
        ps = GetComponentInChildren<ParticleSystem>();
        line = this.renderer as LineRenderer;
    }
	
	// Update is called once per frame
	void Update () {
        shootTimer += Time.deltaTime;
        if (shootTimer >= (1 / shootRate))
        {
            ShootStart();
        }
	}

    void ShootStart()
    {
        shootTimer -= (1 / shootRate);

        light.enabled = true;
        ps.Stop();
        ps.Play();
        line.enabled = true;
        line.SetPosition(0, transform.position);

        Ray ray = new Ray(transform.position, transform.forward);
        RaycastHit hitInfo;
        if (Physics.Raycast(ray, out hitInfo))
        {
            line.SetPosition(1, hitInfo.point);
            if (hitInfo.collider.tag == Tags.enemy)
            {
                EnemyHealth enemyHealth = hitInfo.collider.GetComponent<EnemyHealth>();
                if (enemyHealth != null)
                {
                    enemyHealth.TakeDamage(damagePerShot, hitInfo.point);
                }
            }
        }
        else
        {
            line.SetPosition(1, transform.position + transform.forward * range);
        }
        audio.Play();
        Invoke("ShootEnd", 0.05f);
    }

    public void ShootEnd()
    {
        light.enabled = false;
        line.enabled = false;
    }
}
